package com.wzu.servlet;

import com.wzu.pojo.Book;
import com.wzu.service.BookService;
import com.wzu.service.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 处理图书列表请求的Servlet
 */
@WebServlet("/bookList")
public class BookServlet extends HttpServlet {
    // 业务逻辑服务层对象
    private BookService bookService = new BookServiceImpl();

    /**
     * 处理GET请求，返回图书列表页面
     *
     * @param request  请求对象，包含客户端的请求信息
     * @param response 响应对象，用于向客户端发送响应
     * @throws ServletException 如果Servlet遇到异常
     * @throws IOException      如果发生输入或输出异常
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型和字符编码
        response.setContentType("text/html;charset=UTF-8");
        // 获取响应输出流，用于输出HTML内容
        PrintWriter out = response.getWriter();

        // 调用服务层方法获取所有图书信息
        List<Book> bookList = bookService.getAllBooks();

        // 输出HTML开始部分
        out.println("<html><body>");
        out.println("<h2>图书列表</h2>");
        // 输出图书列表表格的样式和表头
        out.println("<table border='1'>");
        out.println("<tr><th>图书ID</th><th>书名</th><th>作者</th><th>出版社</th><th>出版年份</th><th>ISBN</th><th>价格</th><th>描述</th><th>分类ID</th><th>库存数量</th><th>可用数量</th></tr>");
        // 遍历图书列表，输出每本图书的信息
        for (Book book : bookList) {
            out.println("<tr>");
            out.println("<td>" + book.getBook_id() + "</td>");
            out.println("<td>" + book.getTitle() + "</td>");
            out.println("<td>" + book.getAuthor() + "</td>");
            out.println("<td>" + book.getPublisher() + "</td>");
            out.println("<td>" + book.getPublication_year() + "</td>");
            out.println("<td>" + book.getIsbn() + "</td>");
            out.println("<td>" + book.getPrice() + "</td>");
            out.println("<td>" + book.getDescription() + "</td>");
            out.println("<td>" + book.getCategory_id() + "</td>");
            out.println("<td>" + book.getStock_quantity() + "</td>");
            out.println("<td>" + book.getAvailable_quantity() + "</td>");
            out.println("</tr>");
        }
        // 输出表格和HTML结束部分
        out.println("</table>");
        out.println("</body></html>");
    }
}
